import { init, h } from 'snabbdom'
// 1. 导入模块
import style from 'snabbdom/modules/style'
import attributes from 'snabbdom/modules/attributes'
import eventlisteners from 'snabbdom/modules/eventlisteners'
import { pathToFileURL } from 'url'
// 2. 注册模块
let patch = init([
  style,
  eventlisteners,
  attributes,
])
// 3. 使用 h() 函数的第二个参数传入模块需要的数据（对象）

let data = [
  {
    rank: 1,
    title: 'Javascript',
    description: 'JavaScript (/ˈdʒɑːvəˌskrɪpt/[6]), often abbreviated as JS, is a high-level, dynamic, weakly typed, object-based, multi-paradigm, and interpreted programming language',
  },
  {
    rank: 3,
    title: 'Java',
    description: 'Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented,[14] and specifically designed to have as few implementation dependencies as possible.'
  },
  {
    rank: 2,
    title: 'Python',
    description: 'Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991.'
  },
  {
    rank: 4,
    title: 'C++',
    description: 'A widely used object-oriented programming language based on C.'
  }
]


let tableData = () => data.map(i => {
  return h('tr', [
    ...Object.keys(i).map(m => {
      return h('td', i[m])
    }),
    h('td', {
      style: {
        textAlign: 'center',
        cursor: 'pointer',
        color: '#e4393c'
      },
      on: {
        click: () => deleteHandle(i['title'])
      },
      key: i['title']
    }, 'x')
  ])
})

const table = document.getElementById('table')

let patchTableVnode = () => h('table', {
  style: {
    borderCollapse: 'collapse'
  },
  attrs: {
    border: 1,
  }
}, [
  h('tr', [
    h('th', {
      on: {
        click: () => sortHandle('rank')
      }
    },'Rank'),
    h('th',{
      on: {
        click: () => sortHandle('title')
      }
    },'Title'),
    h('th', {
      on: {
        click: () => sortHandle('description')
      }
    }, 'Description'),
    h('th', 'Operation')
  ]),
  ...tableData()
])

let oldVnode = patch(table, patchTableVnode())

function deleteHandle(title) {
  data = data.filter(i => i.title != title)
  oldVnode = patch(oldVnode, patchTableVnode())
}

function sortHandle(sortKey) {
  data.sort((a,b) => {
    return a[sortKey] - b[sortKey]
  })

  oldVnode = patch(oldVnode, patchTableVnode())
}
